import Fail from '../Pages/403.page'
import React from "react";
import {Tooltip} from 'antd'
import {btnConfig, menuConfig, RejectStyleEnum} from '../Config/auth.config'

const authConfig = [...btnConfig,...menuConfig];
// 能够访问的 路由路径，包括不需要授权的，和有授权的两部分
const authedUrl:string[] = ['/'];

interface AuthorizedProps {
    pathname :string;
    children: any;
}
export const Authorized :React.FC<AuthorizedProps> = props => {
    let path = props.pathname;
    if(path && path.length>1 && path.endsWith("/")){
        path = path.substring(0,path.length-1);
    }
    if (authedUrl.includes(path)) {
        return props.children;
    }
    return <Fail />;
};
interface WidthDisabledProps{
  disabled:boolean;
  onClick?:()=>void;
}

/**
 * 权限自动判断的高阶组件
 * 适用于 antd 的组件：Button Input Menu 等带 disabled 属性的组件
 * 使用方式：
 *  const EditButton = withAuth("btn_report_del")(Button);
 *  <EditButton onClick={()=>console.info("wo shi anniu ")}>我是按钮</EditButton>
 * @param authId 授权id 参考 /config/authorize.config.ts 的配置
 * @param Wrapper 包裹的子组件
 */
export function withAuth(authId:string, Wrapper:  React.ComponentType<WidthDisabledProps>){
    let authItem = authConfig.find(it=>it.key===authId);
    if(!authItem){
        throw authId+ " : authId 不合格";
    }
    // 无需授权
    if(!authItem.auth ) {
      return class extends React.Component{
        render(): React.ReactNode {
          return(
            <Wrapper  disabled={false}  {...this.props} />
          )

        }
      }
    }
    if( authItem.reject === RejectStyleEnum.none){
      return class extends React.Component{
        render(): React.ReactNode {
          return <div />;
        }
      }
    }
     if( authItem.reject === RejectStyleEnum.tooltip){
       return class extends React.Component{
         render(): React.ReactNode {
           return(<Tooltip title='您无权限操作，请联系管理员！'>
                <Wrapper  disabled={false} {...this.props}  onClick={()=>null}/>
             </Tooltip>)

         }
       }
     }
     if( authItem.reject === RejectStyleEnum.disabled){
       return class extends React.Component{
         render(): React.ReactNode {
           return <Wrapper {...this.props}  disabled={true}/>;
         }
       }
     }
    throw authId+ " : authItem.reject  不合格";

}
